/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

// import { CommandDialog } from "nextcax-components";
// import { Icon } from 'nextcax-components';
import { wsApi } from '@app-cad/server';
import { Box, Button, FormGroup } from '@mui/material';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useState } from 'react';
import styled from 'styled-components';
// import { BaseCommand } from 'nextcax-app';
// import { Picker } from 'nextcax-picker';
// import { pickedModelData } from 'nextcax-types';
import {
  BaseCommand,
  CENTEREVENTS,
  CommandDialog,
  EventsRes,
  Icon,
  pickedModelData,
} from '@amcax/base';
import { Picker3D, PickerMgr } from '@amcax/renderer';
import { eventCenterManager } from '@app-base/common/events/EventCenterManager';

// 合并
const SelectLayout = styled.div`
  width: 100%;

  .select {
    display: flex;
    flex-direction: column;
    margin: 10px 0px;
    background: rgba(91, 95, 199, 0.1);
    width: 100%;
    border: none;
    border-radius: 4px;
    cursor: cell;
    padding-left: 0.5em;
    padding: 4px 12px 12px;

    .body {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .placeholder {
      color: #a2a2a2;
    }

    .close-button {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 20px;
      height: 20px;
      border-radius: 4px;
      border: none;
      outline: none;
      cursor: pointer;
      background: none;

      &:hover {
        background: #ccc;
      }

      &:focus {
        border-color: grey;
        border-style: dashed;
        border-width: 1px;
      }
    }
  }

  .active {
    outline: rgb(91, 95, 199) solid 1.5px;
  }
`;

interface CompoundDialogProps {
  title: string;
  onClose: () => void;
}

// interface UserData {
//   pickedObject: any;
//   models: any[];
// }

function CompoundDialog({ title, onClose }: CompoundDialogProps) {
  const [canExecute, setCanExecute] = useState(false);
  const [models, setModels] = useState<any[]>([]); // 将合并的物体
  let selectedModels: pickedModelData[];

  useEffect(() => {
    eventCenterManager.activeEventCenter
      .setState('compound')
      .on(CENTEREVENTS.POINTERMOVE, onMouseMove)
      .on(CENTEREVENTS.POINTERUP, pointerUpEvent)
      .addExit(exit);

    return () => {
      exit();
    };
  }, []);

  useAsyncEffect(async () => {
    setCanExecute(models.length > 0);
  }, [models]);

  const onMouseMove = (e: EventsRes) => {
    const picker = PickerMgr.getPicker<Picker3D>('3d');
    if (e.button.onLeft) {
      picker.marqueeSelection(e);
    } else {
      picker.pick(e, { model: true });
    }
  };
  const pointerUpEvent = (e: EventsRes) => {
    if (!e.button.onLeft) {
      return;
    }
    const picker = PickerMgr.getPicker<Picker3D>('3d');
    if (e.idsMap && e.idsMap.size > 0) {
      picker.selectModel(e.event as PointerEvent);
      picker.selectModel(e.event as PointerEvent);
    } else {
      picker.clickNull();
      picker.clickNull();
    }
    picker.marqueePointerUp();
    selectedModels = Array.from(picker.getSelectedModels().values());
    setModels(selectedModels);
  };

  const handleExecute = async () => {
    let dxids: string[] = [];
    if (models.length > 0) {
      dxids = models.map(({ idInfo }) => idInfo.o);
    } else {
      dxids = [];
    }
    if (dxids.length > 0) {
      await wsApi.createCompound(dxids);
    }
    onClose();
  };

  const handleSelectedModeDelete = (id: string) => {
    const picker = PickerMgr.getPicker<Picker3D>('3d');
    picker.uncheckModels([id]);
    selectedModels = Array.from(picker.getSelectedModels().values());
    setModels(selectedModels);
  };

  const exit = () => {
    const picker = PickerMgr.getPicker<Picker3D>('3d');
    eventCenterManager.activeEventCenter
      .off(CENTEREVENTS.POINTERMOVE, onMouseMove)
      .off(CENTEREVENTS.POINTERUP, pointerUpEvent)
      .setDefault();

    picker.init();
    onClose();
  };

  const Select = ({ title }) => {
    return (
      <div className='select active'>
        <div className='label'>{title}</div>
        {models.length > 0 ? (
          <>
            {models.map((model) => {
              return (
                <div
                  className='body'
                  key={model.idInfo.o}
                >
                  {model.objInfo.label}
                  <button
                    className='close-button'
                    onClick={() => handleSelectedModeDelete(model.idInfo.o)}
                  >
                    <Icon name='close' />
                  </button>
                </div>
              );
            })}
          </>
        ) : (
          <div className='placeholder'>{`[请选择${title}]`}</div>
        )}
      </div>
    );
  };

  return (
    <CommandDialog
      title={title}
      onClose={onClose}
      placement='topLeft'
    >
      <Box
        sx={{
          padding: '0 10px',
          width: '200px',
        }}
      >
        <FormGroup>
          <SelectLayout>
            <Select title='图形' />
          </SelectLayout>
          <Box
            sx={{
              padding: '5px 0',
              display: 'flex',
              justifyContent: 'flex-end',
            }}
          >
            <Button
              size='small'
              variant='contained'
              onClick={handleExecute}
              disabled={!canExecute}
            >
              执行
            </Button>
          </Box>
        </FormGroup>
      </Box>
    </CommandDialog>
  );
}

export const cmdCompound: BaseCommand = {
  id: 'CmdCompound',
  label: 'command.compound',
  icon: 'commands/feature/compound',
  create: (label: string, onClose: () => void) => (
    <CompoundDialog
      title={i18n.t(label)}
      onClose={onClose}
    />
  ),
};
